package com.youxin.busfoundation.common.qiniu;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.youxin.busfoundation.common.GlobalConfig;

/**
 * 上传到七牛云接口
 * @author yingde.cao
 * @date 2017年12月7日
 * @version 1.0
 */
public class UploadQiniuUtils {
	/**
	 * 
	 * @param bucket 类似文件夹
	 * @param bytes 文件二进制
	 * @param fileName 文件名称
	 * @return String 文件名称
	 * @throws QiniuException
	 */
	public static String upload(String bucket, byte[] bytes, String fileName) throws QiniuException {
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone0());
		// ...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);
		// ...生成上传凭证，然后准备上传
		String accessKey = GlobalConfig.QINYUN_ACCESS_KEY;
		String secretKey = GlobalConfig.QINYUN_SECRET_KEY;
		// String bucket = GlobalConfig.QINYUN_BUCKET_CP_DELEGATE;
		// 默认不指定key的情况下，以文件内容的hash值作为文件名
		// String key = null;
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);

		Response response = uploadManager.put(bytes, fileName, upToken);
		// 解析上传成功的结果
		DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
		return putRet.key;

	}

}
